package com.katesoft.scale4j.rttp.spring;

import com.katesoft.scale4j.common.lock.IDistributedLockProvider;
import com.katesoft.scale4j.rttp.internal.RttpHazelcastBridgeAwareImpl;
import net.jcip.annotations.ThreadSafe;

import java.util.concurrent.locks.Lock;

/**
 * This is extended annotation session factory that will not allow concurrent database update(if
 * schemaUpdate flag is set to true).
 * 
 * @author kate2007
 */
@ThreadSafe
public class RttpAnnotationSessionFactoryLock extends RttpHazelcastBridgeAwareImpl implements
         IDistributedLockProvider {
   public static final String RTTP_SCHEMA_DB_UPDATE_DONE = "rttp.schema.db.update.done";

   @Override
   public void markWorkDone() {
      if (getBridge().getHazelcastInstance().getLifecycleService().isRunning()) {
         getBridge().updateAtomicBoolean(RTTP_SCHEMA_DB_UPDATE_DONE, true);
      }
   }

   @Override
   public boolean isWorkDone() {
      return getBridge().getHazelcastInstance().getLifecycleService().isRunning()
               && getBridge().getAtomicBoolean(RTTP_SCHEMA_DB_UPDATE_DONE).get();
   }

   @Override
   public Lock lockFor(final String key) {
      if (getBridge().getHazelcastInstance().getLifecycleService().isRunning()) {
         return getBridge().getHazelcastInstance().getLock(key);
      }
      throw new IllegalStateException(String.format("hazelcast instance %s is not running",
               getBridge().getHazelcastInstance()));
   }
}
